package tool.workflow.fsSoft

import akka.stream.Materializer
import command.CommandExec
import dao._
import implicits.Implicits._
import play.api.i18n.Messages
import play.api.libs.ws.WSClient
import shared.pojo.WorkflowMission.{EachBorutaData, FsData}
import shared.tool.DefaultPickle
import tool.Pojo._
import tool._
import tool.plot.BorutaBox
import tool.softT._
import tool.workflow.fsSoft.AllFsSoft.FSSoftBT
import utils.Utils

import java.io.File
import scala.collection.immutable.SeqMap
import upickle.default._

/**
 * Created by yz on 3/12/2020
 */
object FSBoruta extends FSSoftBT with BorutaSoftBT {

  override lazy val messageName: String = "borutaAna"

  def produceSubConfigFile(workspaceDir: File, data: EachBorutaData) = {
    val subConfigFile = new File(workspaceDir, "calculate_config.json")
    DefaultPickle.write(data).toFile(subConfigFile)
  }


  override def produceInput(workspaceDir: File, resultDir: File, index: Int, parentNodeStr: String, id: String)(
    implicit dao: MyDao,messages: Messages): Unit = {
    val groupFile = new File(workspaceDir.getParentFile, "group.txt")
    val value = Utils.configFile2Json(workspaceDir.getParentFile)
    val data = value.transform(reader[FsData]).boruta(index)
    val groups =data.groups
    groupFile.txtLines.lineSeqMap.filter { map =>
      groups.contains(map("ClassNote"))
    }.csvLines.toTxtFile(new File(workspaceDir, "group.txt"))
    FeatureSelectionTool.produceSubInputFile(workspaceDir, parentNodeStr)
    produceSubConfigFile(workspaceDir, data)
  }

  override def resultDeal(workspaceDir: File, resultDir: File, index: Int)(implicit ws: WSClient, materializer: Materializer, messages: Messages): Unit = {
    val needConvertFileNamePrefixs = List("Decision_Boxplot")
    val convertCommands = Tool.fileConvertCommandsIfExist(workspaceDir, needConvertFileNamePrefixs)
    CommandExec().exec { b =>
      CommandData(workspace = workspaceDir, commands = convertCommands, runFileName = "convert.sh")
    }
  }

  override def getCommandData(workspaceDir: File, resultDir: File, index: Int): List[CommandData] = {
    val solutionFile = new File(Tool.dataDir, "color_solution/color_solution_1.txt")
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    val standardFile = Tool.getStandardFile(workspaceDir)
    val inputMetabolites=Tool.inputMetabolites(workspaceDir)
    val command =if(inputMetabolites.nonEmpty) {
      s"""
         |${"Rscript".condaPath()} ${Tool.rPath.unixPath}/standard.R
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "boruta.R").unixPath} --i ${standardFile.unixPath}
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "boruta_filter.R").unixPath}
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "boruta_plot.R").unixPath} --pc ${BorutaBox.configFileName}
           """.stripMargin
    }else ""
    List(CommandData(workspaceDir, List(command)))
  }

}
